#pragma once
#include <string>
#include <vector>
#include <assert.h>
#include <algorithm>
/* 实现异步写数据，引入缓冲区，生产者往缓冲区放数据，消费者取数据
为了解决频繁的读写锁冲突问题，引入双缓冲区---只有在读缓冲区为空&&写缓冲区不为空的时候才进行交换缓冲区
缓冲区:
    vector<string >记录格式化后的消息
    push()  ->copy函数支持多条消息的写入
    pop()-> 删除数据
    writeable   可写的空间
    readable() size()-wirtesize();
    swap() 交换缓冲取&&和指针
    ensureEnoughSpace() 扩容机制: 双倍增长，如果超过阈值，就低速增长

*/
#define BUFFER_DEFAULT_SIZE 1024 * 1024 * 1     // 缓冲区起始默认1M
#define BUFFER_INCREAMENT_SIZE  1* 1024 * 1024   // 低速增长速度默认1M
#define BUFFER_THRESHOULD_VALUE 3 * 1024 * 1024 // 阈值默认3M  
namespace ns_logger
{
    class Buffer
    {
    public:
        //缓冲区默认大小是1M
        Buffer(size_t capacity = BUFFER_DEFAULT_SIZE)
            : _buffer(capacity), _write_index(0), _read_idex(0) {}

        void Push(const char *data, size_t len)
        {
            // 扩容机制
            EnsureEnoughSpace(len);
            std::copy(data, data + len, &_buffer[_write_index]);
            _write_index += len;
            //到这边存在问题
        }

        void Pop(size_t len)
        {
            _read_idex += len;
            assert(_read_idex <= _write_index);
        }
        const char* GetFront() { return &_buffer[_read_idex]; }
        bool Empty() { return _write_index == _read_idex; }
        // 可读的空间
        size_t Readable()
        {
            return _write_index - _read_idex;
        }
        size_t Writeable()
        {
            return _buffer.size() - _write_index;
        }
        void ReadMove(size_t len)
        {
            assert(_read_idex+len<=_write_index);
            _read_idex+=len;
        }
        void WriteMove(size_t len)
        {
            assert(_write_index+len<_buffer.size());
            _write_index+=len;
        }

        void Swap(Buffer &buffer)
        {
            _buffer.swap(buffer._buffer);
            std::swap(_read_idex, buffer._read_idex);
            std::swap(_write_index, buffer._write_index);
        }

        void ReSet(){
            _read_idex=_write_index=0;
        }

    private:
        void EnsureEnoughSpace(size_t len)
        {
            // 检查是否扩容
            if (len + _write_index < _buffer.size())
                return;
            // 扩容的大小
            size_t newsize;
            if (_buffer.size() <BUFFER_THRESHOULD_VALUE)
            {
                newsize = _buffer.size() * 2 + len;
            }
            // 低速扩容
            else
            {
                newsize = _buffer.size() + len + BUFFER_INCREAMENT_SIZE;
            }
            _buffer.resize(newsize);
        }

    private:
        std::vector<char> _buffer;
        size_t _read_idex;
        size_t _write_index;
    };
};